﻿using Microsoft.AspNetCore.Http;
using SXFramWork.Core;
using System;
using System.Collections.Generic;
using System.Text;

namespace SXFramWork.Core
{
    [Singleton]
    public class LoginInfo : ILoginInfo
    {
        private readonly IHttpContextAccessor _accessor;

        public LoginInfo(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
        /// <summary>
        /// 用户Id
        /// </summary>
        public virtual string UserId
        {
            get
            {
                var id = _accessor?.HttpContext?.User?.FindFirst(ClaimNames.UserId);
                if (id != null && id.Value.NotNull())
                {
                    return id.Value;
                }
                return string.Empty;
            }
        }

        /// <summary>
        /// 请求平台
        /// </summary>
        public Platform Platform
        {
            get
            {
                var pt = _accessor?.HttpContext?.User?.FindFirst(ClaimNames.Platform);
                if (pt != null && pt.Value.NotNull())
                {
                    return (Platform)pt.Value.To_Int();
                }

                return Platform.UnKnown;
            }
        }


        /// <summary>
        /// 用户名
        /// </summary>
        public string UserName
        {
            get
            {
                var name = _accessor?.HttpContext?.User?.FindFirst(ClaimNames.UserName);

                if (name != null && name.Value.NotNull())
                {
                    return name.Value;
                }

                return "";
            }
        }

        /// <summary>
        /// 用户名
        /// </summary>
        public string RoleName
        {
            get
            {
                var name = _accessor?.HttpContext?.User?.FindFirst(ClaimNames.RoleName);

                if (name != null && name.Value.NotNull())
                {
                    return name.Value;
                }

                return "";
            }
        }

        /// <summary>
        /// 获取当前用户IP(包含IPv和IPv6)
        /// </summary>
        public string IP
        {
            get
            {
                if (_accessor?.HttpContext?.Connection == null)
                    return "";
                return _accessor.HttpContext.Connection.RemoteIpAddress.ToString();
            }
        }

    }
}
